<template>
	<view class="main-container">

		<view class="carsoul-container">
			<u-swiper :list="swiperList" height="320px"></u-swiper>
		</view>
		<view class="list-container">
			<u-list>
				<u-list-item class="item-row">
					<view class="item-content">
						<view class="item-label">课程名</view>
						<view class="item-value">{{ course.courseName || '-' }}</view>
					</view>
				</u-list-item>
				<u-list-item class="item-row">
					<view class="item-content">
						<view class="item-label">已售</view>
						<view class="item-value">{{ nowList.soldCount || 0 }}</view>
					</view>

				</u-list-item>
				<u-list-item class="item-row">
					<view class="item-content">
						<view class="item-label">库存</view>
						<view class="item-value">{{ nowList.totalLimit || 0 }}</view>
					</view>

				</u-list-item>
				<u-list-item class="item-row">
					<view class="item-content">
						<view class="item-label">课程开始时间</view>
						<view class="item-value">{{ course.startTime || '-' }}</view>
					</view>

				</u-list-item>
				<u-list-item class="item-row">
					<view class="item-content">
						<view class="item-label">课程结束时间</view>
						<view class="item-value">{{ course.endTime || '-' }}</view>
					</view>
				</u-list-item>

				<u-list-item class="item-row">
					<view class="item-content">
						<view class="item-label">课程类型</view>
						<view class="item-value">{{ course.courseType }}</view>
					</view>
				</u-list-item>
				<u-list-item class="item-row">
					<view class="item-content">
						<view class="item-label">课时</view>
						<view class="item-value">{{ course.hours || '0' }}</view>
					</view>
				</u-list-item>
				<u-list-item class="item-row">
					<view class="item-content">
						<view class="item-label">课程简介</view>
						<view class="item-value content-textarea">
							<!-- 使用textarea组件展示简介，设置为只读 -->
							<textarea :value="course.courseDescription || '-' " disabled class="textarea-style"
								placeholder="暂无简介"></textarea>
						</view>
					</view>
				</u-list-item>
			</u-list>
		</view>
		<!-- 底部固定区域 -->
		<view class="fixed-bottom-area">
			<!-- 实名认证提示区域 -->
			<view class="auth-tip-area" v-if="!isAuthenticated">
				<view class="auth-tip flex-row">
					<u-icon name="volume" class="auth-icon"></u-icon>
					<text>您尚未完成实名认证，无法参与秒杀</text>
				</view>
				<text class="real-container" @click="showAuthDialog">实名认证</text>
			</view>
			<!-- 价格显示区域 -->
			<view class="price-area" v-if="nowList.price !== undefined">
				<text class="original-price" v-if="nowList.price">¥{{ nowList.price }}</text>
				<text class="seckill-price">¥{{ nowList.seckillPrice || '0' }}</text>
				<!-- 添加倒计时组件 -->
				<view class="countdown-container" v-if="isLimit">
					<u-count-down :time="remainingTime" format="HH:mm:ss" autoStart
						@finish="handleCountDownEnd"></u-count-down>
				</view>
			</view>

			<!-- 添加加载状态 -->
			<view v-else class="loading-indicator">加载中...</view>
			<!-- 底部按钮区域 -->
			<view class="fixed-bottom-btn">
				<view class="favorite-btn">
					<text class="iconfont"
						:class="{'icon-collect-active': isFavorite, 'icon-collect': !isFavorite, 'active': isFavorite}"></text>
					<text>收藏</text>
				</view>
				<view class="seckill-btn">
					<u-button type="primary" class="full-width-btn" :disabled="isSeckillAvailable"
						@click="handleSeckill">{{btnName}}</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		queryDetailBySeckillId,
		queryCourseById,
		queryStuAuthen,
		querySeckillNum,
		secKillCourse,querySeckillResult,queryUserLimit
	} from '@/api/seckill.js'
	export default {
		data() {
			return {
				studentId: 3, //学生ID
				seckillId: 3, //秒杀课程ID
				
				swiperList: [
					"http://1.94.233.8:19000/education-bucket/7beb3ccc-6caa-4459-bce9-98ef5e37b7da.jpg",
					"http://1.94.233.8:19000/education-bucket/7beb3ccc-6caa-4459-bce9-98ef5e37b7da.jpg",
					"http://1.94.233.8:19000/education-bucket/7beb3ccc-6caa-4459-bce9-98ef5e37b7da.jpg",
				],
				
				nowList: {},
				course: {},
				isFavorite: false, // 收藏状态
				isSeckillAvailable: true, // 秒杀按钮可用状态
				loading: false, // 加载状态
				remainingTime: 0,
				btnName: '', //按钮名称
				isEnd: false, //活动是否已经结束
				isAuthenticated: false, // 实名认证状态，true为已认证
				num: 0,
				isSeckillLoading: false,//秒杀处理中的加载状态
				isLimit:false,//用户是否限购
				baseUrl: 'http://localhost:8011',
			}
		},
		created() {
			this.initSeckill();
			
			this.handleStuAuthen();
		},
		methods: {
			async initSeckill() {
				try {
				    this.seckillId = wx.getStorageSync("seckillId");
				    const res = await this.queryDetailBySeckillId(this.seckillId);
				    this.nowList = res.data.data.secKillDetail;
				    await this.handleQueryCourse(this.nowList.courseId);
				    this.startTime = this.nowList.startTime;
				    this.endTime = this.nowList.endTime;
				    this.currTime = new Date();
				    this.judgeSeckillStatus(this.currTime, this.startTime, this.endTime);
				    this.handleStudentLimit();
				  } catch (err) {
				    console.log("查询秒杀课程详情失败" + err);
				  }
			},
			async queryDetailBySeckillId(seckillId) {
			  return new Promise((resolve, reject) => {
			    uni.request({
			      url: `${this.baseUrl}/seckill/queryDetailBySeckillId`,
			      method: 'GET',
			      data: { seckillId },
			      success: (res) => resolve(res),
			      fail: (err) => reject(err)
			    });
			  });
			},
			async handleQueryCourse(courseId) {
			  try {
			    const res = await uni.request({
			      url: `${this.baseUrl}/seckill/queryCourseById`,
			      method: 'GET',
			      data: { courseId },
			    });
			    // 1. 判断业务状态码（根据你的后端规范调整）
			    if (res.data.code !== 200) { // 假设200为成功状态码
			      throw new Error(res.data.message || '操作失败');
			    }
			    
			    // 2. 验证数据完整性
			    if (!res.data.data.course) {
			      throw new Error('课程数据不存在');
			    }
			    
			    // 3. 处理正常业务逻辑
			    this.course = res.data.data.course;
			  } catch (err) {
			    console.log("查询秒杀课程详情失败", err);
			    uni.showToast({
			      title: err.message || '获取课程信息失败',
			      icon: 'none'
			    });
			  }
			},
			//发起秒杀
			handleSeckill() {
				
				//验证是否是实名
				if (!this.isAuthenticated) {
					//没有实名，提示请先完成实名认证
					uni.showToast({
						title: '请先完成实名认证',
						icon: 'none',
						duration: 2000
					});
					return;
				};
				// 进入秒杀处理状态，禁用按钮
				  this.isSeckillAvailable = true;
				  this.btnName = '正在提交...';
				  this.isSeckillLoading = true;
				  
				  
				this.handlequerySecNum();




			},
			//查询redis里面剩余的库存
			async handlequerySecNum() {
			  try {
			    
			    const res = await uni.request({
			      url: `${this.baseUrl}/seckill/querySeckillNum`, 
			      method: 'GET',
			      data: {
			        seckillId: this.seckillId
			      }
			    });
		
			    const num = res.data.data.number;
			    
			    
			    let message = "秒杀取消";
			    if (num < 1) {
			      message = "库存不足!!!";
			    } else {
			      message = `剩余库存: ${num}`;
			    }
			    
			    uni.showModal({
			      title: '秒杀提示',
			      content: message,
			      cancelText: '取消',
			      confirmColor: '#409EFF',
			      success: async (res) => { // 注意这里添加了 async 关键字
			        if (res.confirm && num > 0) {
			          uni.showToast({
			            title: '正在跳转到支付页面',
			            icon: 'loading',
			            duration: 1500
			          });
			          
			          // 确定购买
			          await this.handleConfirmSeckill();
			          // 跳转示例：uni.navigateTo({ url: '/pages/auth/real-name' });
			        } else {
			          let cancelMsg, showFail;
			          if (num < 1) {
			            cancelMsg = "库存不足，请下次再买";
			            showFail = true;
			          }
			          
			          uni.showToast({
			            title: showFail ? cancelMsg : "取消购买",
			            icon: 'none',
			            duration: 1500
			          });
					  this.initSeckill();
			        }
			      }
			    });
			  } catch (error) {
			    console.error("查询秒杀库存失败:", error);
			    uni.showToast({
			      title: '网络请求失败，请重试',
			      icon: 'none',
			      duration: 1500
			    });
			  }
			},
			//倒计时结束时的回调
			handleCountDownEnd() { 
				if (this.isEnd) return;
				this.isSeckillAvailable = !this.isSeckillAvailable;
				if (this.btnName == "进行中") {
					this.btnName = "已结束"
				} else if (this.btnName == "即将开始") {
					this.btnName = "进行中";
					//倒计时结束时间
					this.startTime = this.nowList.startTime;
					this.endTime = this.nowList.endTime;
					this.currTime = new Date();
					this.judgeSeckillStatus(this.currTime, this.startTime, this.endTime);

				} else {
					this.btnName = "无法秒杀";
					this.isSeckillAvailable = true;
				}
			},
			// 日期格式化函数
			formatDate(dateString) {
				if (!dateString) return '';

				// 处理带时区的日期字符串
				const date = new Date(dateString);

				// 获取年月日
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');

				return `${year}年${month}月${day}日`;
			},

			//根据开始时间，当前时间，秒杀时间来显示秒杀状态
			judgeSeckillStatus(curr, startTime, endTime) {
				const start = new Date(startTime);
				// const start = new Date("Fri May 30 2025 14:07:00 GMT+0800 (GMT+08:00)");
				const end = new Date(endTime);
				// const end = new Date("Thu Jun 05 2025 20:30:00 GMT+0800 (GMT+08:00)");
				let status = '';
				let message = '';
				if (curr < start) {
					//活动未开始
					console.log(start);

					this.remainingTime = start - curr;
					this.isSeckillAvailable = true;
					this.btnName = "即将开始";


				} else {
					if (curr < end) {
						//活动进行中

						this.remainingTime = end - curr;
						this.btnName = "立即秒杀";
						this.isSeckillAvailable = false;

					} else {
						//活动结束
						this.isEnd = true;
						this.isSeckillAvailable = true;
						this.remainingTime = 0;
						this.btnName = "已结束";
					}
				}
			},
			showAuthDialog() {
				uni.showModal({
					title: '实名认证提示',
					content: '您需要完成实名认证才能参与秒杀活动，是否现在前往认证？',
					confirmText: '前往认证',
					cancelText: '暂不认证',
					confirmColor: '#409EFF',
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '正在跳转到实名认证页面',
								icon: 'loading',
								duration: 1500
							});
							// 跳转示例：uni.navigateTo({ url: '/pages/auth/real-name' });
						} else {
							uni.showToast({
								title: '您可以稍后在个人中心完成认证',
								icon: 'none',
								duration: 1500
							});
						}
					}
				});
			},
			//查询用户实名状态
			async handleStuAuthen() {
			  try {
			    const res = await uni.request({
			      url: `${this.baseUrl}/seckill/queryStuAuthen`, 
			      method: 'GET',
			      data: { studentId: this.studentId }
			    });
				
		
			    const responseData = res.data;
			    // 验证返回结构
			    if (!responseData) {
			      throw new Error('服务器响应异常');
			    }
			    
			    
			    if (responseData.code !== 200) {
			      throw new Error(responseData.message || '查询实名认证失败');
			    }
			    
			    // 更新组件状态
			    this.isAuthenticated = responseData.data.isAuthenticated;
			  } catch (error) {
			    console.error('查询实名认证失败', error);
			    uni.showToast({
			      title: error.message || '获取认证信息失败',
			      icon: 'none'
			    });
			    
			    // 设置默认状态
			    this.isAuthenticated = false;
			  }
			},
			//查询用户限购情况
			async handleStudentLimit() {
			  try {
			    const data = {
			      seckillId: this.nowList.seckillId,
			      studentId: this.studentId,
			      limitCount: this.nowList.studentLimitCount,
			    };
			    
			    const res = await uni.request({
			      url: `${this.baseUrl}/seckill/studentLimit`,
			      method: 'GET',
			      data,
			    });
			    console.log(res);
			    this.isLimit = res.data.data.isLimit; 
			    
			    if (!this.isLimit) {
			      this.btnName = "请勿重复购买";
			      this.isSeckillAvailable = true;
			    }
			  } catch (err) {
			    console.log("查询用户限购情况失败", err);
			  }
			},
			//确定秒杀
			async handleConfirmSeckill() {
			  try {
			    uni.showLoading({
			      title: '秒杀处理中...'
			    });
			
			    const data = {
			      seckillId: this.seckillId,
			      studentId: this.studentId,
			      courseId: this.nowList.courseId,
			      orderAmount: this.nowList.seckillPrice,
			    };
			
			    // 使用 uni.request 替代原有的 secKillCourse 方法
			    const res = await uni.request({
			      url: `${this.baseUrl}/seckill/secKillCourse`, 
			      method: 'POST',
			      data,
			      header: {
			        'Content-Type': 'application/json'
			      }
			    });
			
			    
			    const queryId = res.data.data?.queryId;
			    if (!queryId) {
			      throw new Error('查询ID获取失败');
			    }
			
			    // 开始轮询查询结果
			    await this.pollSeckillResult(queryId);
			  } catch (error) {
			    console.error("秒杀课程失败:", error);
			    uni.hideLoading();
			    uni.showToast({
			      title: error.message || '秒杀请求失败，请稍后再试',
			      icon: 'none'
			    });
			  }
			},
			// 轮询秒杀结果
			async pollSeckillResult(queryId) {
			  let pollCount = 0;
			  const MAX_POLL_COUNT = 30; // 最多轮询30次
			  
			  try {
			    // 显示加载状态
			    uni.showLoading({ title: '处理中...' });
			    
			    
			    while (pollCount < MAX_POLL_COUNT) {
			      
			      const res = await uni.request({
			        url: `${this.baseUrl}/seckill/querySecKillResult`, 
			        method: 'GET',
			        data: { queryId }
			      });
			      
			      console.log('秒杀结果:', res);
			      
			      if (res.data.code === 200) { // 秒杀成功
			        uni.showToast({
			          title: '秒杀成功',
			          icon: 'success'
			        });
			        wx.setStorageSync("orderId", res.data.data.orderId);
					this.initSeckill();
			        // 跳转到订单详情页
			        // uni.navigateTo({ url: `pages/student-center/student-center` });
			        break;
			      } else if (res.data.code === 400) { // 秒杀失败
			        uni.showToast({
			          title: res.data.message || '秒杀失败',
			          icon: 'none'
			        });
					
			        break;
			      } else if (res.data.code === 500) { // 秒杀失败
			        uni.showToast({
			          title: res.data.message || '秒杀失败',
			          icon: 'none'
			        });
					
			        break;
			      }else if (res.data.code === 202) { // 处理中，继续轮询
			        console.log(`第 ${pollCount+1} 次轮询，结果处理中...`);
			      } else {
			        throw new Error('查询结果异常');
			      }
			      
			      pollCount++;
			      // 等待1秒后继续轮询
			      await new Promise(resolve => setTimeout(resolve, 1000));
			    }
			    
			    // 检查是否是因为超时退出循环
			    if (pollCount >= MAX_POLL_COUNT) {
			      throw new Error('秒杀处理超时，请稍后再试');
			    }
			  } catch (err) {
			    console.error("查询秒杀结果失败:", err);
			    uni.showToast({
			      title: err.message || '查询结果失败，请稍后再试',
			      icon: 'none'
			    });
			  } finally {
			    // 隐藏加载状态
			    uni.hideLoading();
			    
			    // 恢复按钮状态
			    this.isSeckillAvailable = false;
			    this.btnName = this.isEnd ? '已结束' : '立即秒杀';
			  }
			}
		}
	}
</script>

<style lang="scss">
	.main-container {
		height: 95vh;
	}

	.carsoul-container {
		max-height: 42vh;
		background-color: greenyellow;
	}

	.list-container {
		margin-top: 20px;
		padding: 0 15px;
	}

	.item-row {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		padding: 15px 0;
		
		border-bottom: 1px solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}
	}

	.item-content {
		display: flex;
		width: 100%;
		justify-content: space-between;
		align-items: flex-start;
		height: 8vh;
		line-height: 8vh;
	}

	.item-label {
		font-weight: 600;
		color: #333;
		min-width: 100px;
		flex-shrink: 0;
		align-self: flex-start;
		padding-top: 5px;
	}

	.item-value {
		color: #666;
		text-align: left;
		flex: 1;
		padding-top: 5px;
		padding-left: 20px;
	}

	/* 文本域样式 */
	.content-textarea {
		width: 100%;
	}

	.textarea-style {
		width: 100%;
		height: 120px;
		padding: 16px;
		box-sizing: border-box;
		border: 1px solid #e0e0e0;
		border-radius: 8px;
		background-color: #ffffff;
		font-size: 14px;
		line-height: 1.6;
		overflow-y: auto;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		font-size: 18px;


		&:hover {
			border-color: #409EFF;
			box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
		}


		&:focus {
			outline: none;
			border-color: #409EFF;
			box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
		}
	}

	/* 底部固定区域 */
	.fixed-bottom-area {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 100;
	}

	/* 价格显示区域 */
	.price-area {
		height: 60rpx;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.original-price {
		color: #999;
		font-size: 24rpx;
		text-decoration: line-through;
		margin-right: 20rpx;
	}

	.seckill-price {
		color: #e64340;
		font-size: 32rpx;
		font-weight: bold;
	}

	/* 倒计时样式 */
	.countdown-container {
		display: inline-flex;
		align-items: center;
		color: #fff;
		font-size: 28rpx;

		padding: 6rpx 12rpx;
		border-radius: 8rpx;
		margin-left: 300rpx;
	}

	/* 底部按钮区域 */
	.fixed-bottom-btn {
		height: 88rpx;
		background-color: #ffffff;
		display: flex;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.favorite-btn,
	.seckill-btn {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.favorite-btn {
		color: #666;
	}

	.favorite-btn .iconfont {
		font-size: 36rpx;
		margin-bottom: 4rpx;
	}

	.favorite-btn.active {
		color: #e64340;
	}

	/* 实名认证提示区域 */
	.auth-tip-area {
		height: 74rpx;
		background-color: #fff8e6;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.auth-tip {
		display: flex;
		align-items: center;
		color: #ff9800;
		font-size: 26rpx;
	}

	.auth-tip .icon-tip {
		margin-right: 10rpx;
		font-size: 28rpx;
	}

	.real-container {
		margin-left: 30px;
		color: #409EFF;
		text-decoration: underline;

	}

	.flex-row {
		display: flex;
		flex-direction: row;
		align-items: center;
	}
</style>